using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using System.Text.RegularExpressions;
using CKY.AgentPlatform.ModelConfigs;
using CKY.AgentPlatform.Agents;
using CKY.AgentPlatform.Common.Types;
using ToolCall = CKY.AgentPlatform.Common.Types.ToolCall;

namespace CKY.AgentPlatform.Services
{
    /// <summary>
    /// 大模型执行服务 - 负责调用各种AI模型
    /// </summary>
    public class ModelExecutionService : ApplicationService, IModelExecutionService
    {
        private readonly IRepository<ModelConfig, Guid> _modelConfigRepository;
        private readonly ILogger<ModelExecutionService> _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IConfiguration _configuration;
        private readonly ModelAdapterManager _adapterManager;
        private readonly ModelAdapterRegistry _adapterRegistry;

        public ModelExecutionService(
            IRepository<ModelConfig, Guid> modelConfigRepository,
            ILogger<ModelExecutionService> logger,
            IHttpClientFactory httpClientFactory,
            IConfiguration configuration,
            ModelAdapterManager adapterManager,
            ModelAdapterRegistry adapterRegistry)
        {
            _modelConfigRepository = modelConfigRepository;
            _logger = logger;
            _httpClientFactory = httpClientFactory;
            _configuration = configuration;
            _adapterManager = adapterManager;
            _adapterRegistry = adapterRegistry;
        }

        /// <summary>
        /// 执行大模型调用
        /// </summary>
        /// <param name="modelConfig">模型配置</param>
        /// <param name="input">执行输入</param>
        /// <returns>模型执行结果</returns>
        public async Task<ModelExecutionResult> ExecuteModelAsync(ModelConfig modelConfig, ModelExecutionInput input)
        {
            var executionId = Guid.NewGuid();
            _logger.LogInformation("开始执行模型调用: {ModelName}, 执行ID: {ExecutionId}",
                modelConfig.Name, executionId);

            try
            {
                // 验证模型配置
                if (!modelConfig.IsValid())
                {
                    throw new InvalidOperationException($"模型配置无效: {modelConfig.Name}");
                }

                // 尝试使用新的适配器架构
                var adapterAttempt = await TryExecuteWithAdapterAsync(modelConfig, input, executionId);
                if (adapterAttempt.Success && adapterAttempt.Result != null)
                {
                    await UpdateModelStatsAsync(modelConfig.Id, adapterAttempt.Result.TokensUsed, adapterAttempt.Result.Success);
                    return adapterAttempt.Result;
                }

                // 回退到旧的调用方式
                _logger.LogWarning("适配器调用失败，回退到传统调用方式: {ModelName}", modelConfig.Name);
                var result = await ExecuteModelLegacyAsync(modelConfig, input, executionId);

                await UpdateModelStatsAsync(modelConfig.Id, result.TokensUsed, result.Success);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "模型调用异常: {ModelName}, 执行ID: {ExecutionId}",
                    modelConfig.Name, executionId);

                await UpdateModelStatsAsync(modelConfig.Id, 0, false);

                return new ModelExecutionResult
                {
                    Success = false,
                    ErrorMessage = ex.Message,
                    TokensUsed = 0
                };
            }
        }

        /// <summary>
        /// 执行OpenAI模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteOpenAIModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var apiUrl = $"{modelConfig.ApiBaseUrl ?? "https://api.openai.com/v1"}/chat/completions";

            // 构建请求消息
            var messages = input.Messages.Select(m => new
            {
                role = m.Role,
                content = m.Content
            }).ToList();

            var requestBody = new
            {
                model = modelConfig.Model,
                messages = messages,
                max_tokens = input.MaxTokens,
                temperature = input.Temperature,
                top_p = modelConfig.TopP,
                frequency_penalty = modelConfig.FrequencyPenalty,
                presence_penalty = modelConfig.PresencePenalty,
                stream = false
            };

            var requestContent = new StringContent(
                JsonSerializer.Serialize(requestBody),
                Encoding.UTF8,
                "application/json"
            );

            // 设置请求头
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {modelConfig.ApiKey}");

            // 发送请求
            var response = await SendRequestWithRetryAsync(
                httpClient,
                HttpMethod.Post,
                apiUrl,
                requestContent,
                modelConfig.MaxRetries,
                executionId
            );

            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new InvalidOperationException($"OpenAI API调用失败: {response.StatusCode}, 错误: {errorContent}");
            }

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

            // 解析响应
            var choice = responseData.GetProperty("choices")[0];
            var message = choice.GetProperty("message");
            var content = message.GetProperty("content").GetString() ?? "";

            // 解析工具调用（如果存在）
            var toolCalls = new List<ToolCall>();
            if (message.TryGetProperty("tool_calls", out var toolCallsElement))
            {
                foreach (var toolCallElement in toolCallsElement.EnumerateArray())
                {
                    var function = toolCallElement.GetProperty("function");
                    var functionName = function.GetProperty("name").GetString();
                    var argumentsJson = function.GetProperty("arguments").GetString();
                    var arguments = JsonSerializer.Deserialize<Dictionary<string, object>>(argumentsJson);

                    toolCalls.Add(new ToolCall
                    {
                        Id = toolCallElement.GetProperty("id").GetString(),
                        Name = functionName,
                        Parameters = arguments
                    });
                }
            }

            // 解析Token使用量
            long tokensUsed = 0;
            if (responseData.TryGetProperty("usage", out var usageElement))
            {
                tokensUsed = usageElement.GetProperty("total_tokens").GetInt64();
            }

            return new ModelExecutionResult
            {
                Success = true,
                Response = content,
                ToolCalls = toolCalls,
                TokensUsed = tokensUsed
            };
        }

        /// <summary>
        /// 执行Anthropic Claude模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteAnthropicModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var apiUrl = $"{modelConfig.ApiBaseUrl ?? "https://api.anthropic.com"}/v1/messages";

            // 构建请求消息
            var messages = input.Messages
                .Where(m => m.Role != "system") // Anthropic不支持系统消息
                .Select(m => new
                {
                    role = m.Role == "assistant" ? "assistant" : "user",
                    content = m.Content
                }).ToList();

            // 获取系统提示词
            var systemPrompt = input.Messages.FirstOrDefault(m => m.Role == "system")?.Content;

            var requestBody = new
            {
                model = modelConfig.Model,
                max_tokens = input.MaxTokens,
                temperature = input.Temperature,
                messages = messages,
                system = systemPrompt
            };

            var requestContent = new StringContent(
                JsonSerializer.Serialize(requestBody),
                Encoding.UTF8,
                "application/json"
            );

            // 设置请求头
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Add("x-api-key", modelConfig.ApiKey);
            httpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");

            // 发送请求
            var response = await SendRequestWithRetryAsync(
                httpClient,
                HttpMethod.Post,
                apiUrl,
                requestContent,
                modelConfig.MaxRetries,
                executionId
            );

            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new InvalidOperationException($"Anthropic API调用失败: {response.StatusCode}, 错误: {errorContent}");
            }

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

            // 解析响应
            var content = "";
            if (responseData.TryGetProperty("content", out var contentElement))
            {
                if (contentElement.ValueKind == JsonValueKind.Array)
                {
                    foreach (var item in contentElement.EnumerateArray())
                    {
                        if (item.TryGetProperty("text", out var textElement))
                        {
                            content += textElement.GetString();
                        }
                    }
                }
            }

            // 解析Token使用量
            long tokensUsed = 0;
            if (responseData.TryGetProperty("usage", out var usageElement))
            {
                tokensUsed = usageElement.GetProperty("input_tokens").GetInt64() +
                             usageElement.GetProperty("output_tokens").GetInt64();
            }

            return new ModelExecutionResult
            {
                Success = true,
                Response = content,
                ToolCalls = new List<ToolCall>(), // Anthropic工具调用需要单独实现
                TokensUsed = tokensUsed
            };
        }

        /// <summary>
        /// 执行Google Gemini模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteGoogleModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var apiUrl = $"{modelConfig.ApiBaseUrl ?? "https://generativelanguage.googleapis.com/v1beta"}/models/{modelConfig.Model}:generateContent";

            // 构建请求消息
            var systemPrompt = input.Messages.FirstOrDefault(m => m.Role == "system")?.Content;
            var userMessages = input.Messages.Where(m => m.Role != "system").ToList();

            // 构建contents
            var contents = new List<object>();
            foreach (var msg in userMessages)
            {
                contents.Add(new
                {
                    role = msg.Role == "assistant" ? "model" : "user",
                    parts = new[] { new { text = msg.Content } }
                });
            }

            var requestBody = new
            {
                contents = contents,
                generationConfig = new
                {
                    maxOutputTokens = input.MaxTokens,
                    temperature = input.Temperature,
                    topP = modelConfig.TopP
                },
                systemInstruction = systemPrompt != null ? new
                {
                    parts = new[] { new { text = systemPrompt } }
                } : null
            };

            var requestContent = new StringContent(
                JsonSerializer.Serialize(requestBody),
                Encoding.UTF8,
                "application/json"
            );

            // 设置请求头
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Add("x-goog-api-key", modelConfig.ApiKey);

            // 发送请求
            var response = await SendRequestWithRetryAsync(
                httpClient,
                HttpMethod.Post,
                apiUrl,
                requestContent,
                modelConfig.MaxRetries,
                executionId
            );

            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new InvalidOperationException($"Google API调用失败: {response.StatusCode}, 错误: {errorContent}");
            }

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

            // 解析响应
            string responseText = "";
            if (responseData.TryGetProperty("candidates", out var candidatesElement))
            {
                var candidate = candidatesElement.EnumerateArray().First();
                if (candidate.TryGetProperty("content", out var contentElement))
                {
                    if (contentElement.TryGetProperty("parts", out var partsElement))
                    {
                        foreach (var part in partsElement.EnumerateArray())
                        {
                            if (part.TryGetProperty("text", out var textElement))
                            {
                                responseText += textElement.GetString();
                            }
                        }
                    }
                }
            }

            // 解析Token使用量
            long tokensUsed = 0;
            if (responseData.TryGetProperty("usageMetadata", out var usageElement))
            {
                tokensUsed = usageElement.GetProperty("totalTokenCount").GetInt64();
            }

            return new ModelExecutionResult
            {
                Success = true,
                Response = responseText,
                ToolCalls = new List<ToolCall>(), // Gemini工具调用需要单独实现
                TokensUsed = tokensUsed
            };
        }

        /// <summary>
        /// 执行百度文心一言模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteBaiduModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            // 实现百度文心一言的API调用逻辑
            // 这里需要根据百度API的具体要求实现
            throw new NotImplementedException("百度文心一言模型调用尚未实现");
        }

        /// <summary>
        /// 执行阿里云通义千问模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteAlibabaModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            // 实现阿里云通义千问的API调用逻辑
            // 这里需要根据阿里云API的具体要求实现
            throw new NotImplementedException("阿里云通义千问模型调用尚未实现");
        }

        /// <summary>
        /// 执行智谱AI模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteZhipuAIModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            // 实现智谱AI的API调用逻辑
            // 这里需要根据智谱AI API的具体要求实现
            throw new NotImplementedException("智谱AI模型调用尚未实现");
        }

        /// <summary>
        /// 执行月之暗面模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteMoonshotModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            // 实现月之暗面的API调用逻辑
            // 这里需要根据Moonshot API的具体要求实现
            throw new NotImplementedException("月之暗面模型调用尚未实现");
        }

        /// <summary>
        /// 执行自定义模型
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteCustomModelAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            var httpClient = _httpClientFactory.CreateClient();
            var apiUrl = modelConfig.ApiBaseUrl;

            if (string.IsNullOrWhiteSpace(apiUrl))
            {
                throw new InvalidOperationException("自定义模型未配置API地址");
            }

            // 构建通用请求格式
            var requestBody = new
            {
                model = modelConfig.Model,
                messages = input.Messages.Select(m => new
                {
                    role = m.Role,
                    content = m.Content
                }),
                max_tokens = input.MaxTokens,
                temperature = input.Temperature,
                stream = false
            };

            var requestContent = new StringContent(
                JsonSerializer.Serialize(requestBody),
                Encoding.UTF8,
                "application/json"
            );

            // 设置请求头
            httpClient.DefaultRequestHeaders.Clear();
            if (!string.IsNullOrWhiteSpace(modelConfig.ApiKey))
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {modelConfig.ApiKey}");
            }

            // 发送请求
            var response = await SendRequestWithRetryAsync(
                httpClient,
                HttpMethod.Post,
                apiUrl,
                requestContent,
                modelConfig.MaxRetries,
                executionId
            );

            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new InvalidOperationException($"自定义模型API调用失败: {response.StatusCode}, 错误: {errorContent}");
            }

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseData = JsonSerializer.Deserialize<JsonElement>(responseContent);

            // 尝试解析通用响应格式
            string responseText = "";
            if (responseData.TryGetProperty("choices", out var choicesElement))
            {
                var choice = choicesElement.EnumerateArray().First();
                if (choice.TryGetProperty("message", out var messageElement))
                {
                    responseText = messageElement.GetProperty("content").GetString() ?? "";
                }
            }
            else if (responseData.TryGetProperty("response", out var responseElement))
            {
                responseText = responseElement.GetString() ?? "";
            }

            return new ModelExecutionResult
            {
                Success = true,
                Response = responseText,
                ToolCalls = new List<ToolCall>(),
                TokensUsed = 0 // 自定义模型可能不返回Token使用量
            };
        }

        /// <summary>
        /// 带重试的请求发送
        /// </summary>
        private async Task<HttpResponseMessage> SendRequestWithRetryAsync(
            HttpClient httpClient,
            HttpMethod method,
            string url,
            HttpContent content,
            int maxRetries,
            Guid executionId)
        {
            var lastException = new Exception();

            for (int attempt = 1; attempt <= maxRetries; attempt++)
            {
                try
                {
                    var request = new HttpRequestMessage(method, url)
                    {
                        Content = content
                    };

                    // 设置超时
                    var timeout = TimeSpan.FromSeconds(30); // 默认30秒
                    if (content is StringContent stringContent)
                    {
                        // 可以从配置中解析超时设置
                    }

                    var cts = new CancellationTokenSource(timeout);
                    var response = await httpClient.SendAsync(request, cts.Token);

                    return response;
                }
                catch (Exception ex) when (attempt < maxRetries)
                {
                    lastException = ex;
                    _logger.LogWarning(ex, "请求失败，准备重试: {Attempt}/{MaxRetries}, 执行ID: {ExecutionId}",
                        attempt, maxRetries, executionId);

                    // 等待一段时间再重试
                    await Task.Delay(1000 * attempt);
                }
            }

            throw lastException;
        }

        /// <summary>
        /// 尝试使用适配器架构执行模型调用
        /// </summary>
        private async Task<(bool Success, ModelExecutionResult Result)> TryExecuteWithAdapterAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            try
            {
                // 构建调用配置
                var invocationConfig = BuildInvocationConfig(modelConfig);

                // 构建调用请求
                var invocationRequest = BuildInvocationRequest(input, modelConfig);

                // 选择最佳适配器
                var adapter = _adapterManager.SelectBestAdapter(invocationConfig);

                // 执行调用
                var invocationResponse = await adapter.InvokeAsync(invocationConfig, invocationRequest, executionId.ToString());

                // 转换响应格式
                var result = ConvertToModelExecutionResult(invocationResponse);
                return (result.Success, result);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "适配器调用失败: {ModelName}, 错误: {ErrorMessage}", modelConfig.Name, ex.Message);
                return (false, null);
            }
        }

        /// <summary>
        /// 构建调用配置
        /// </summary>
        private ModelInvocationConfig BuildInvocationConfig(ModelConfig modelConfig)
        {
            var config = new ModelInvocationConfig
            {
                ApiMode = GetApiMode(modelConfig),
                NativeApiEndpoint = modelConfig.ApiBaseUrl,
                OpenAICompatibleEndpoint = GetOpenAICompatibleEndpoint(modelConfig),
                EnableFallback = true,
                FallbackTimeoutMs = 10000,
                MaxRetries = modelConfig.MaxRetries,
                Capabilities = GetProviderCapabilities(modelConfig.Provider),
                SupportedModels = new List<string> { modelConfig.Model }
            };

            // 设置模型特定参数
            config.ModelSpecificParams["ApiKey"] = modelConfig.ApiKey;
            config.ModelSpecificParams["Provider"] = modelConfig.Provider.ToString();

            // 设置自定义头
            if (!string.IsNullOrWhiteSpace(modelConfig.ApiKey))
            {
                config.CustomHeaders["Authorization"] = $"Bearer {modelConfig.ApiKey}";
            }

            return config;
        }

        /// <summary>
        /// 获取API模式
        /// </summary>
        private ModelApiMode GetApiMode(ModelConfig modelConfig)
        {
            // 从配置中读取API模式，默认为Auto
            if (modelConfig.AdditionalConfig?.TryGetValue("ApiMode", out var apiModeValue) == true)
            {
                if (Enum.TryParse<ModelApiMode>(apiModeValue.ToString(), out var apiMode))
                {
                    return apiMode;
                }
            }

            // 根据提供商推断默认模式
            return modelConfig.Provider switch
            {
                ModelProvider.ZhipuAI => ModelApiMode.Auto, // 智谱AI支持多种模式
                ModelProvider.OpenAI => ModelApiMode.OpenAICompatible,
                ModelProvider.Anthropic => ModelApiMode.Native,
                ModelProvider.Google => ModelApiMode.Native,
                ModelProvider.Custom => ModelApiMode.OpenAICompatible,
                _ => ModelApiMode.Auto
            };
        }

        /// <summary>
        /// 获取OpenAI兼容端点
        /// </summary>
        private string GetOpenAICompatibleEndpoint(ModelConfig modelConfig)
        {
            // 如果配置了专门的OpenAI兼容端点
            if (modelConfig.AdditionalConfig?.TryGetValue("OpenAICompatibleEndpoint", out var endpoint) == true)
            {
                return endpoint.ToString();
            }

            // 对于智谱AI，提供默认的OpenAI兼容端点
            if (modelConfig.Provider == ModelProvider.ZhipuAI)
            {
                return "https://open.bigmodel.cn/api/paas/v4/chat/completions";
            }

            // 默认使用原生API端点
            return modelConfig.ApiBaseUrl;
        }

        /// <summary>
        /// 获取提供商能力
        /// </summary>
        private ModelProviderCapabilities GetProviderCapabilities(ModelProvider provider)
        {
            return provider switch
            {
                ModelProvider.OpenAI => ModelProviderCapabilities.Streaming |
                                      ModelProviderCapabilities.FunctionCalling |
                                      ModelProviderCapabilities.JsonMode |
                                      ModelProviderCapabilities.SystemPrompt |
                                      ModelProviderCapabilities.ToolCalling |
                                      ModelProviderCapabilities.Vision,

                ModelProvider.Anthropic => ModelProviderCapabilities.Streaming |
                                         ModelProviderCapabilities.FunctionCalling |
                                         ModelProviderCapabilities.SystemPrompt,

                ModelProvider.Google => ModelProviderCapabilities.Streaming |
                                      ModelProviderCapabilities.FunctionCalling |
                                      ModelProviderCapabilities.SystemPrompt |
                                      ModelProviderCapabilities.Vision,

                ModelProvider.ZhipuAI => ModelProviderCapabilities.Streaming |
                                       ModelProviderCapabilities.FunctionCalling |
                                       ModelProviderCapabilities.JsonMode |
                                       ModelProviderCapabilities.SystemPrompt |
                                       ModelProviderCapabilities.ToolCalling,

                ModelProvider.Custom => ModelProviderCapabilities.Streaming |
                                      ModelProviderCapabilities.FunctionCalling |
                                      ModelProviderCapabilities.JsonMode,

                _ => ModelProviderCapabilities.None
            };
        }

        /// <summary>
        /// 构建调用请求
        /// </summary>
        private ModelInvocationRequest BuildInvocationRequest(ModelExecutionInput input, ModelConfig modelConfig)
        {
            return new ModelInvocationRequest
            {
                Model = modelConfig.Model,
                Messages = input.Messages.Select(m => new CKY.AgentPlatform.ModelConfigs.ChatMessage
                {
                    Role = m.Role,
                    Content = m.Content
                }).ToList(),
                MaxTokens = input.MaxTokens,
                Temperature = input.Temperature,
                TopP = modelConfig.TopP,
                FrequencyPenalty = modelConfig.FrequencyPenalty,
                PresencePenalty = modelConfig.PresencePenalty,
                Stream = false,
                UserId = input.UserId != Guid.Empty ? input.UserId.ToString() : "",
                SessionId = input.SessionId != Guid.Empty ? input.SessionId.ToString() : "",
                Metadata = new Dictionary<string, object>
                {
                    { "ExecutionType", "AdapterBased" },
                    { "ModelProvider", modelConfig.Provider.ToString() },
                    { "ModelName", modelConfig.Name }
                }
            };
        }

        /// <summary>
        /// 转换响应格式
        /// </summary>
        private ModelExecutionResult ConvertToModelExecutionResult(ModelInvocationResponse invocationResponse)
        {
            return new ModelExecutionResult
            {
                Success = invocationResponse.Success,
                Response = invocationResponse.Response?.Content ?? "",
                ErrorMessage = invocationResponse.Error?.Message,
                TokensUsed = invocationResponse.Usage?.TotalTokens ?? 0,
                ToolCalls = invocationResponse.ToolCalls?.Select(tc => new ToolCall
                {
                    Id = tc.Id,
                    Type = tc.Type,
                    FunctionName = tc.FunctionName,
                    FunctionArguments = tc.FunctionArguments,
                    Name = tc.Name ?? tc.FunctionName,
                    Parameters = tc.Parameters ?? tc.FunctionArguments
                }).ToList() ?? new List<ToolCall>(),
                Metadata = new Dictionary<string, object>
                {
                    { "UsedApiMode", invocationResponse.UsedApiMode },
                    { "ResponseTimeMs", invocationResponse.ResponseTimeMs },
                    { "ExecutionId", invocationResponse.Id }
                }
            };
        }

        /// <summary>
        /// 传统模型调用方式（回退用）
        /// </summary>
        private async Task<ModelExecutionResult> ExecuteModelLegacyAsync(ModelConfig modelConfig, ModelExecutionInput input, Guid executionId)
        {
            // 根据提供商调用不同的模型
            return modelConfig.Provider switch
            {
                ModelProvider.OpenAI => await ExecuteOpenAIModelAsync(modelConfig, input, executionId),
                ModelProvider.Anthropic => await ExecuteAnthropicModelAsync(modelConfig, input, executionId),
                ModelProvider.Google => await ExecuteGoogleModelAsync(modelConfig, input, executionId),
                ModelProvider.Baidu => await ExecuteBaiduModelAsync(modelConfig, input, executionId),
                ModelProvider.Alibaba => await ExecuteAlibabaModelAsync(modelConfig, input, executionId),
                ModelProvider.ZhipuAI => await ExecuteZhipuAIModelAsync(modelConfig, input, executionId),
                ModelProvider.Moonshot => await ExecuteMoonshotModelAsync(modelConfig, input, executionId),
                ModelProvider.Custom => await ExecuteCustomModelAsync(modelConfig, input, executionId),
                _ => throw new NotSupportedException($"不支持的模型提供商: {modelConfig.Provider}")
            };
        }

        /// <summary>
        /// 测试模型连接（使用适配器）
        /// </summary>
        public async Task<ModelConnectionTestResult> TestConnectionAsync(ModelConfig modelConfig)
        {
            try
            {
                var invocationConfig = BuildInvocationConfig(modelConfig);
                var validation = await _adapterManager.ValidateAdapterConfigAsync(invocationConfig);

                return new ModelConnectionTestResult
                {
                    Success = validation.IsValid,
                    ResponseTimeMs = validation.ConnectionTest?.ResponseTimeMs ?? 0,
                    ErrorMessage = validation.ErrorMessage,
                    AdapterName = validation.Adapter?.Name,
                    ApiMode = invocationConfig.ApiMode,
                    Details = validation.Details
                };
            }
            catch (Exception ex)
            {
                return new ModelConnectionTestResult
                {
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取适配器统计信息
        /// </summary>
        public AdapterRegistryStatistics GetAdapterStatistics()
        {
            return _adapterRegistry.GetStatistics();
        }

        /// <summary>
        /// 获取支持的模型提供商列表
        /// </summary>
        public IReadOnlyList<ModelProviderRegistration> GetSupportedProviders()
        {
            return _adapterRegistry.GetAllProviders();
        }

        /// <summary>
        /// 更新模型使用统计
        /// </summary>
        private async Task UpdateModelStatsAsync(Guid modelConfigId, long tokensUsed, bool success)
        {
            try
            {
                var modelConfig = await _modelConfigRepository.GetAsync(modelConfigId);
                modelConfig.UpdateUsageStats(tokensUsed, success);
                await _modelConfigRepository.UpdateAsync(modelConfig);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新模型统计失败: {ModelConfigId}", modelConfigId);
            }
        }
    }

    /// <summary>
    /// 模型连接测试结果
    /// </summary>
    public class ModelConnectionTestResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 响应时间（毫秒）
        /// </summary>
        public long ResponseTimeMs { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 使用的适配器名称
        /// </summary>
        public string AdapterName { get; set; }

        /// <summary>
        /// 使用的API模式
        /// </summary>
        public ModelApiMode ApiMode { get; set; }

        /// <summary>
        /// 详细信息
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();
    }
}